<template>
  <div class="hot-games-container">
    <div class="hot-games-header">
      <h2 class="hot-games-title">{{ title }}</h2>
      <div class="pagination">
        <el-button class="pagination-btn" type="primary" :icon="ArrowLeftBold" solid @click="prevPage"
          :disabled="isLoading || !carouselRef || !canGoPrev" />
        <el-button class="pagination-btn" type="primary" :icon="ArrowRightBold" solid @click="nextPage"
          :disabled="isLoading || !carouselRef || !canGoNext" />
      </div>
    </div>

    <!-- 其余代码保持不变 -->
    <div class="games-wrapper">
      <el-carousel ref="carouselRef" indicator-position="none" arrow="never" :autoplay="false" :loop="false"
        @change="handleCarouselChange">
        <el-carousel-item v-for="(pageGames, pageIndex) in paginatedGames" :key="pageIndex">
          <div class="games-grid">
            <el-card v-for="(game, index) in pageGames" :key="game.id || `${pageIndex}-${index}`" class="game-card"
              shadow="never">
              <GameCard :game="game" @play="handleGamePlay" />
            </el-card>
          </div>
        </el-carousel-item>
      </el-carousel>

      <!-- 加载中动画 -->
      <div v-if="isLoading" class="loading-overlay">
        <div class="loading-spinner">
          <el-icon class="loading-icon">
            <Loading />
          </el-icon>
          <span>加载中...</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import GameCard from '@/components/GameCard.vue'
import { ArrowLeftBold, ArrowRightBold, Loading } from '@element-plus/icons-vue'
import { gameApi } from '@/api/game'
import { ElCarousel, ElCarouselItem } from 'element-plus'

const route = useRoute()
const router = useRouter()

const props = defineProps({
  layouts: {
    type: Array,
    default: () => []
  },
  title: {
    type: String,
    default: ''
  },
  hashMore: {
    type: Boolean,
    default: false
  },
  contentId: {
    type: Number,
    default: 0
  }
})

const emit = defineEmits(['pageChange'])

// 分页相关状态
const currentPage = ref(1)
const carouselRef = ref(null)
const itemsPerPage = 3
const isLoading = ref(false)

const initialLayouts = ref([...props.layouts])
const localLayouts = ref([...props.layouts])
const localHashMore = ref(!!props.hashMore)

// 将游戏数据分页
const paginatedGames = computed(() => {
  const pages = []
  for (let i = 0; i < localLayouts.value.length; i += itemsPerPage) {
    pages.push(localLayouts.value.slice(i, i + itemsPerPage))
  }
  return pages
})

watch(() => props.layouts, (v) => {
  initialLayouts.value = Array.isArray(v) ? [...v] : []
  if (currentPage.value === 1) localLayouts.value = initialLayouts.value
})

watch(() => props.hashMore, (v) => {
  localHashMore.value = !!v
})
// 添加这两个计算属性来控制按钮的禁用状态
const canGoPrev = computed(() => {
  // 当前页码大于1时才能上一页
  return currentPage.value > 1
})

const canGoNext = computed(() => {
  // 当前页码小于总页数时才能下一页
  return paginatedGames.value.length > 0 && currentPage.value < paginatedGames.value.length
})
const navigateToGameDetail = (item) => {
  router.push({
    path: `/cloudGaming/detail/${item.id}`,
  })
}

const handleGamePlay = (game) => {
  console.log('游戏播放事件:', game.title)
}

const getCategoryGames = () => {
  isLoading.value = true
  let params = {
    page: 1,
    rows: 100,
    categoryId: props.contentId
  }
  gameApi.getGameListByCategory(params).then(res => {
    console.log("获取分类游戏列表:", res);
    const list = (res && res.games) ? res.games : (res && res.data) ? res.data : []
    localLayouts.value = Array.isArray(list) ? list : []

    nextTick(() => {
      isLoading.value = false
    })
  }).catch(error => {
    console.error("获取分类游戏列表失败:", error);
    isLoading.value = false
  })
}


const handleCarouselChange = (index) => {
  currentPage.value = index + 1
  emit('pageChange', currentPage.value)
}
// 添加这两个方法来处理翻页
const prevPage = () => {
  if (carouselRef.value && carouselRef.value.prev) {
    carouselRef.value.prev()
  } else if (carouselRef.value && carouselRef.value.data && carouselRef.value.data.prev) {
    carouselRef.value.data.prev()
  }
}

const nextPage = () => {
  if (carouselRef.value && carouselRef.value.next) {
    carouselRef.value.next()
  } else if (carouselRef.value && carouselRef.value.data && carouselRef.value.data.next) {
    carouselRef.value.data.next()
  }
}
onMounted(() => {
  getCategoryGames();
})
</script>

<style lang="scss" scoped>
.hot-games-container {
  margin-top: 60px;

  .hot-games-header {
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .hot-games-title {
      font-size: 20px;
      font-weight: 600;
      color: #ffffff;
      margin: 0;
    }

    .pagination-btn {
      width: 30px;
      height: 30px;
      border: none !important;
      background: rgba(35, 37, 39, 1);
      box-sizing: border-box;
      border-radius: 4px;
      color: rgba(79, 79, 79, 1);

      &:hover:not(:disabled) {
        color: rgba(148, 148, 149, 1);
      }

      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }
  }

  .games-wrapper {
    overflow: hidden;
    position: relative;
    width: 100%;
  }

  .games-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
  }

  // 加载中动画样式
  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10;
  }

  .loading-spinner {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    color: #ffffff;

    .loading-icon {
      font-size: 40px;
      animation: rotate 1s linear infinite;
    }

    span {
      font-size: 16px;
    }
  }

  @keyframes rotate {
    from {
      transform: rotate(0deg);
    }

    to {
      transform: rotate(360deg);
    }
  }
}
</style>